<template>
  <div>
    <div v-show="firstStep">
      <el-form :model="basicInfo" :rules="rules" ref="basicInfo" label-width="120px">
        <div class="detail-info" style="margin-top: 50px">
          <div class="form-item" style="padding-bottom:60px">
            <h4>基本信息</h4>
            <el-form-item label="所属设备" required>
              <el-select v-model="basicInfo.limit_client" style="width:220px">
                <el-option label="全部" value="0"></el-option>
                <el-option label="PC订货" value="10"></el-option>
                <el-option label="惠配通" value="20"></el-option>
                <el-option label="惠付通" value="30"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分公司" required>
              <el-input v-model="this.showBranchName" disabled="disabled" style="width:220px"></el-input>
            </el-form-item>
            <el-form-item label="所属部门" required>
              <el-input v-model="this.showDeptName" disabled="disabled" style="width:220px"></el-input>
            </el-form-item>
            <el-form-item label="所属仓库" prop="limit_store_id">
              <el-select v-model="basicInfo.limit_store_id" placeholder="所属仓库" style="width:220px">
                <el-option v-for="(item, index) in storeList" :label="item.name" :value="item.id" :key="index"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="客资类型" required>
              <el-select v-model="basicInfo.limit_user_type" style="width:220px" @change="userTypeChange">
                <el-option label="普通超市" value="1"></el-option>
                <el-option label="企业" value="2"></el-option>
                <el-option label="一批" value="3"></el-option>
                <el-option label="二批" value="8"></el-option>
              </el-select>
              <!--<el-select v-model="basicInfo.limit_user_type"-->
              <!--placeholder="客资类型" style="width:220px"-->
              <!--:loading="customerTypeLoading"-->
              <!--@change="userTypeChange" @visible-change="visibleChange">-->
                 <!--&lt;!&ndash;<el-option value="1" label="普通超市"></el-option>&ndash;&gt;-->
                <!--<el-option v-for="(item, index) in customerTypeList"-->
                <!--:key="index"-->
                <!--:label="item.name"-->
                <!--:value="item.id.toString()"></el-option>-->
              <!--</el-select>-->
            </el-form-item>
            <el-form-item label="客户标签">
              <el-select v-model="basicInfo.limit_usertypetag_id" multiple style="width:220px">
                <el-option v-for="(item, index) in labelList"
                   :label="item.labelName"
                   :value="item.labelCode"
                   :disabled="item.disabled"
                   :key="index">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标签类型" required v-show="basicInfo.limit_user_type === '1'">
              <el-radio-group v-model="basicInfo.promotion_icon">
                <el-radio :label="0">常规</el-radio>
                <el-radio :label="3">惊爆</el-radio>
                <el-radio :label="2">满购</el-radio>
                <el-radio :label="1">特价</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="basicInfo.limit_user_type !== '1'" label="所属品牌" prop="firstCate" style="float:left;">
              <el-select clearable v-model="basicInfo.firstCate" @change="handleChooseGoods($event, '2', '1')" @visible-change="visibleChange" style="width:130px" placeholder="一级分类">
                <el-option v-for="(item, index) in firstClassifyGroup" :label="item.cateName" :value="item.id" :key="index"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="basicInfo.limit_user_type !== '1'" label="" label-width="20px" prop="secondCate" style="float:left">
              <el-select clearable v-model="basicInfo.secondCate" @change="handleChooseGoods($event, '3', '1')" @visible-change="visibleChange" style="width:130px" placeholder="二级分类">
                <el-option v-for="(item, index) in secondClassifyGroup" :label="item.cateName" :value="item.id" :key="index"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="basicInfo.limit_user_type !== '1'" label="" label-width="20px" prop="limit_brand_id" style="float:left">
              <el-select clearable v-model="basicInfo.limit_brand_id" style="width:130px" placeholder="品牌" @visible-change="visibleChange">
                <el-option v-for="(item, index) in brandGroup" :label="item.brandName" :value="item.brandId" :key="index"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="basicInfo.limit_user_type === '1'" label="商品类型" prop="limit_product_type" >
              <el-select v-model="basicInfo.limit_product_type" placeholder="商品类型"
              style="width:220px" @change="resetTable" @visible-change="visibleChange">
                <el-option label="常规" value="10"></el-option>
                <el-option label="冷链" value="40"></el-option>
                <el-option label="鲜食" value="42"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="detail-info" style="margin-top: 50px">
          <div class="form-item">
            <h4>活动信息</h4>
            <el-form-item label="套餐名称" prop="promotion_name" >
              <el-input v-model="basicInfo.promotion_name" placeholder="套餐名称" style="width:220px"></el-input>
            </el-form-item>
            <el-form-item label="活动起止时间" prop="startStopTime" >
              <el-date-picker v-model="basicInfo.startStopTime" :editable="false" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="活动起止时间" @change="daterangeFormat" style="width:350px"
              :picker-options="pickerExpirationDate"
                              :default-time="['00:00:00', '23:59:59']"></el-date-picker>
            </el-form-item>
            <el-form-item label="起购金额" prop="limit_satisfy_money">
              <el-input v-model="basicInfo.limit_satisfy_money" placeholder="输入金额，不输则不限制" style="width:220px"></el-input>
            </el-form-item>
            <!-- <el-form-item label="可销售上限" prop="limit_sell_count">
              <el-input v-model="basicInfo.limit_sell_count" placeholder="输入数量，不输则不限制" style="width:220px"></el-input>
            </el-form-item> -->
            <el-form-item label="限购条件" required >
              <el-select v-model="basicInfo.limit_buy_filter" @change="filterChange" placeholder="限购条件" style="width:220px">
                <el-option label="每单" value="1"></el-option>
                <el-option label="全程" value="2"></el-option>
                <el-option label="不限" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="basicInfo.limit_buy_filter !== '3'" label="限购数量" prop="limit_buy_count" required >
              <el-input v-model="basicInfo.limit_buy_count" placeholder="限购数量" style="width:220px"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="describe" >
              <el-input v-model="basicInfo.describe" type="textarea" placeholder="请填写活动描述" style="width:220px"></el-input>
            </el-form-item>
            <el-form-item label="图片选择" required >
              <el-upload
                class="avatar-uploader"
                :action="url"
                name="imageFile"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                accept=".jpg,.png">
                <img v-if="basicInfo.cover_pic" :src="imgHost + '/' + basicInfo.cover_pic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div style="margin: 20px auto 80px; width: 17%">
        <el-button @click="nextStep('basicInfo')" type="success">下一步</el-button>
        <el-button @click="cancel(menuId, 1)" type="danger">取消</el-button>
      </div>
    </div>
    <div v-show="secondStep">
      <div class="detail-info" style="margin-top: 50px">
        <div class="form-item">
          <h4>商品信息</h4>
          <el-button type="primary" @click="handleChooseGoods('', '1')"><i class="el-icon-plus"></i>商品</el-button>
          <el-table :data="goodsList" border style="margin-top:20px;width: 100%" :row-class-name="tableRowClassName">
            <el-table-column prop="productid" label="商品ID" align="center" width="65px"></el-table-column>
            <el-table-column prop="name" label="商品名称" align="center" min-width="180px"></el-table-column>
            <el-table-column prop="saleunit" label="销售单位" align="center" width="80px">
              <template scope="scope">
                <span v-if="scope.row.saleunitFlag === true" :class="{ red: isRed, green: isGreen }">{{scope.row.saleunit}}</span>
                <span v-else>{{scope.row.saleunit}}</span>
              </template>
            </el-table-column>
            <el-table-column label="销售规格" align="center" width="80px">
              <template scope="scope">
                <span v-if="scope.row.salenormFlag === true" :class="{ red: isRed, green: isGreen }">{{scope.row.salenorm}}</span>
                <span v-else>{{scope.row.salenorm}}</span>
              </template>
            </el-table-column>
            <el-table-column label="系统售价" align="center" width="80px">
              <template scope="scope">
                <span v-if="scope.row.salepriceFlag"  :class="{ red: isRed, green: isGreen }">{{scope.row.saleprice}}</span>
                <span v-else>{{scope.row.saleprice}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="cgprice" label="上次入库成本价" align="center" width="120px"></el-table-column>
            <el-table-column prop="oldml" label="原毛利" align="center" width="70px"></el-table-column>
            <el-table-column label="促销价" align="center" width="100px">
              <template scope="scope">
                <el-input v-model="scope.row.promotionprice" @blur="valueToTable(scope.row, scope.$index, '促销价')" placeholder="促销价"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="cxml" label="促销毛利" align="center" width="80px"></el-table-column>
            <el-table-column prop="cxmls" label="毛利损失" align="center" width="80px"></el-table-column>
            <el-table-column label="数量" align="center" width="80px">
              <template scope="scope">
                <el-input v-model="scope.row.num" @blur="valueToTable(scope.row, scope.$index, '数量')" placeholder="数量"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="促销费用" align="center" width="180px">
              <template scope="scope">
                <el-select v-model="scope.row.promotionfeetype" @change="handleChangeSalesCosts($event, scope.$index)"  placeholder="请选择促销费用" :loading="saleCostLoading">
                  <el-option v-for="(item, index) in salesCostsList" :key="index" :label="item.promotionName" :value="item.id.toString()" ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="供应商承担金额" width="120px">
              <template scope="scope">
                <el-input v-model="scope.row.providerholdprice" @blur="valueToTable(scope.row, scope.$index, '供应商承担金额')" :disabled="scope.row.providerDisabled" placeholder="供应商承担金额"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="60px" fixed="right">
              <template scope="scope">
                <el-button type="text" @click="deleteCoupon(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div v-if="changeGoodFlag" class="detail-info" style="margin-top: 50px">
        <div class="form-item">
          <h4>异常商品信息</h4>
          <el-button type="primary" @click="changeGoodsClick">一键修改</el-button>
          <el-table :data="changeGoodsList" border style="margin-top:20px">
            <el-table-column prop="stateName" label="状态" align="center"></el-table-column>
            <!--<el-table-column label="状态" align="center">-->
              <!--<template scope="scope">-->
                <!--<span v-if="scope.row.canNotSale === true">下架</span>-->
                <!--<span v-else>调价</span>-->
              <!--</template>-->
            <!--</el-table-column>-->
            <el-table-column prop="productid" label="商品ID" align="center"></el-table-column>
            <el-table-column prop="name" label="商品名称" align="center"></el-table-column>
            <el-table-column prop="saleunit" label="销售单位" align="center"></el-table-column>
            <el-table-column prop="salenorm" label="销售规格" align="center"></el-table-column>
            <el-table-column prop="saleprice" label="系统售价" align="center"></el-table-column>
          </el-table>
        </div>
      </div>
      <!-- <el-button type="primary" @click="computeComb">计算</el-button> -->
      <div class="detail-info" style="margin-top: 50px">
        <div class="form-item">
          <h4>套餐信息</h4>
            <el-table :data="comboInfo" border >
              <el-table-column label="套餐原价" prop="tcyuanjia" align="center"></el-table-column>
              <el-table-column label="套餐成本价" prop="tcchengbenjia" align="center"></el-table-column>
              <el-table-column label="套餐原毛利" prop="tcyuanmaoli" align="center"></el-table-column>
              <el-table-column label="套餐促销价" prop="tccuxiaojia" align="center"></el-table-column>
              <el-table-column label="套餐促销毛利" prop="tccuxiaomaoli" align="center"></el-table-column>
              <el-table-column label="套餐促销毛利率" align="center">
                <template scope="scope">{{scope.row.tccuxiaomaolilv}}%</template>
              </el-table-column>
              <el-table-column label="套餐毛利损失" prop="tcmaolisunshi" align="center"></el-table-column>
            </el-table>
        </div>
      </div>
      <div class="detail-info">
        <div class="form-item" style="margin-bottom:0">
          <h4>备注</h4>
          <el-input style="width:400px" type="textarea" placeholder="请输入备注" v-model="basicInfo.remark"></el-input>
        </div>
      </div>
      <div style="margin: 20px auto 20px; width: 20%">
        <el-button @click="onSubmit(2, 'basicInfo')" type="success">提交</el-button>
        <el-button @click="onSubmit(1, 'basicInfo')" type="warning">暂存</el-button>
        <el-button @click="goBack" type="danger">返回</el-button>
      </div>
      <el-dialog title="选择商品" size="large" :visible.sync="goodsDialog" custom-class="goodsDialog">
        <el-form>
          <el-row style="margin-top:20px">
            <el-col :span="9">
              <el-form-item label="分类">
                <el-select clearable v-model="chooseGoodsInfo.firstCate"
                @change="handleChooseGoods($event, '2')" style="width:110px"
                :disabled="selectDisabled" placeholder="一级分类">
                  <el-option v-for="(item, index) in firstClassifyGroup" :label="item.cateName" :value="item.id" :key="index"></el-option>
                </el-select>
                <el-select clearable v-model="chooseGoodsInfo.secondCate"
                @change="handleChooseGoods($event, '3')" style="width:110px"
                :disabled="selectDisabled" placeholder="二级分类">
                  <el-option v-for="(item, index) in secondClassifyGroup" :label="item.cateName" :value="item.id" :key="index"></el-option>
                </el-select>
                <el-select clearable v-model="chooseGoodsInfo.thirdCate" style="width:110px"
                :disabled="selectDisabled" placeholder="三级分类">
                  <el-option v-for="(item, index) in threeClassifyGroup" :label="item.cateName" :value="item.id" :key="index"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="品牌">
                <el-select clearable v-model="chooseGoodsInfo.fourCate" :disabled="selectDisabled" style="width:110px" placeholder="品牌">
                  <el-option v-for="(item, index) in brandGroup" :label="item.brandName" :value="item.brandId" :key="index"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="商品ID">
                <el-input v-model="chooseGoodsInfo.hmpId" style="width:110px" placeholder="商品ID"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="商品名称">
                <el-input v-model="chooseGoodsInfo.hmpName" style="width:120px" placeholder="商品名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" @click="searchCouponGoods(isMaster, '搜索')">搜索</el-button>
            </el-col>
          </el-row>
          <el-table ref="table" :data="goodsSearchList" border @selection-change="selectChange" v-loading="searchLoading">
            <el-table-column type="selection" :selectable="checkSelectAble" :reserve-selection="false" align="center" label="全选"></el-table-column>
            <el-table-column prop="productid" align="center" label="商品ID" width="100"></el-table-column>
            <el-table-column prop="name" align="center" label="商品名称" min-width="150"></el-table-column>
            <el-table-column prop="saleunit" align="center" label="单位" width="100"></el-table-column>
            <el-table-column prop="salenorm" align="center" label="规格" width="100"></el-table-column>
            <el-table-column prop="saleprice" align="center" label="系统售价" width="100"></el-table-column>
            <el-table-column prop="cgprice" align="center" label="上次入库成本价" width="120"></el-table-column>
            <el-table-column prop="isActivity" align="center" label="当前活动" width="120"></el-table-column>
            <el-table-column align="center" label="操作" width="100">
              <template scope="scope">
                <el-button v-if="scope.row.operation === 0 && scope.row.isActivity ===''" @click="addCode(scope.row, goodsSearchList[scope.$index])" type="text">添加</el-button>
                <el-button v-if="scope.row.operation === 1 && scope.row.isActivity ===''" @click="recallCode(scope.row, goodsList)"  type="text">撤销</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row>
            <el-col :span="12">
              <el-button type="primary" @click="batchAdd" style="margin-top:20px">批量添加</el-button>
            </el-col>
            <el-col :span="12">
              <el-pagination
                @current-change="handleCurrentChange"
                :page-size="Number(chooseGoodsInfo.pageSize)"
                layout="total, prev, pager, next"
                :total="Number(chooseGoodsInfo.total)"
                style="padding-top:10px;text-align: right;">
              </el-pagination>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import { getInfo, activity } from '../../../../../config/proxy.js'
  import { apiHost, apiURL } from '../../../../../config/settings.js'
  import moment from 'moment'
  export default {
    data () {
      var checkReturnTimes = (rule, value, callback) => { // 验证反多少次
        if (!value) {
          return callback(new Error('限购数量不能为空'))
        } else {
          var re = /^[1-9]\d*$/
          if (!re.test(value)) {
            callback(new Error('请输入大于0的正整数'))
          } else {
            callback()
          }
        }
      }
      var checkReturnTimes2 = (rule, value, callback) => { // 验证反多少次
        if (value) {
          var re = /^[1-9]\d*$/
          if (!re.test(value)) {
            callback(new Error('请输入大于0的正整数'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      var checkReturnMoney = (rule, value, callback) => {
        if (value) {
          var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
          if (!reg.test(value)) {
            callback(new Error('金额入大于0且最多两位小数'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return {
        arr: [],
        labelList: [],
        pickerExpirationDate: { // 截止日期类型禁用时间段
          disabledDate (time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        basicInfo: {
          limit_usertypetag_id: '', // 用户标签
          promotion_icon: 0,       // 标签类型
          limit_client: '0', // 设备类型
          limit_branch_id: '', // 页面展示的公司名id
          limit_department: '', // 页面展示的部门id
          limit_store_id: '', // 所属仓库
          limit_user_type: '1', // 客资类型
          limit_cateid: {
            cateid1: '',
            cateid2: ''
          },
          firstCate: '', // 一级分类
          secondCate: '', // 二级分类
          limit_brand_id: '', // 品牌ID
          limit_product_type: '', // 商品类型
          promotion_name: '', // 套餐名称
          start_time: '', // 活动开始时间
          end_time: '', // 活动结束时间
          limit_satisfy_money: '', // 起购金额
          limit_sell_count: '', // 销售上线
          limit_buy_filter: '1', // 限购条件
          limit_buy_count: '', // 限购数量
          describe: '', // 描述
          remark: '', // 备注
          cover_pic: '', // 封面头图URL
          iscaogao: '', // 是否草稿
          product: '', // 商品
          startStopTime: [] // 活动开始结束时间
        },
        isMaster: 1, // 是否为主商品
        showBranchName: '', // 页面展示的公司名id
        showDeptName: '', // 页面展示的部门id
        firstStep: true,
        secondStep: false,
        storeList: [ // 仓库列表
        ],
        url: '', // 上传图片地址
        imgHost: '', // 上传图片域名
        customerTypeList: [], // 客资类型
        customerTypeLoading: true, // 客资类型加载
        searchLoading: false, // 查询商品loding
        salesCostsList: [], // 促销费用数组
        saleCostLoading: true, // 促销费用loading
        selectSalesType: [], // 选中的促销费用
        goodsList: [], // 商品列表
        changeGoodsList: [], // 调价商品数组
        tableIndex: [], // 调价商品index数组
        goodsListFlag: false, // 商品数组是否显示
        changeGoodFlag: false, // 调价商品是否显示
        isRed: true,
        isGreen: false,
        goodsSearchList: [], // 选择商品列表
        chooseGoodsInfo: { // 选择商品条件
          firstCate: '',
          secondCate: '',
          thirdCate: '',
          fourCate: '',
          hmpId: '',
          hmpName: '',
          page: '1',
          pageSize: '20',
          total: 0
        },
        firstClassifyGroup: [], // 一级分类数组
        secondClassifyGroup: [], // 二级分类数组
        threeClassifyGroup: [], // 三级分类数组
        brandGroup: [], // 品牌数组
        goodsDialog: false, // 商品弹框
        selectDisabled: false, // 一级分类 二级分类 品牌 禁用
        selectGroup: [], // 多选框数组
        comboInfo: [], // 套餐信息数组
        menuId: '', // 菜单id
        isCreateOrUpdate: '',
        text: '',
        detailData: [], // 详情数组
        rules: {
          limit_store_id: [
            { required: true, type: 'number', message: '请选择所属仓库', trigger: 'change' }
          ],
          firstCate: [
            { required: true, type: 'number', message: '请选择一级分类', trigger: 'change' }
          ],
          secondCate: [
            { required: true, type: 'number', message: '请选择二级分类', trigger: 'change' }
          ],
          limit_brand_id: [
            { required: true, type: 'number', message: '请选择品牌', trigger: 'change' }
          ],
          limit_product_type: [
            { required: true, message: '请选择商品类型', trigger: 'change' }
          ],
          promotion_name: [
            { required: true, message: '请输入套餐名称', trigger: 'blur, change' }
          ],
          startStopTime: [
            { type: 'array', required: true, message: '请选择起止时间', trigger: 'change' }
          ],
          radioModel: [
            { required: true, message: '请选择动作跳转', trigger: 'change' }
          ],
          equipments: [
            { required: true, message: '请选择所属设备', trigger: 'change' }
          ],
          limit_buy_count: [ // 限购数量
            {validator: checkReturnTimes, trigger: 'blur'}
          ],
          describe: [
            { required: true, message: '请输入活动描述', trigger: 'blur, change' }
          ],
          limit_sell_count: [ // 可销售上线
            {validator: checkReturnTimes2, trigger: 'blur'}
          ],
          limit_satisfy_money: [ // 起够金额
            {validator: checkReturnMoney, trigger: 'blur'}
          ]
        },
        imgValid: false,
        goodsVaild: false,
        visible: false // select开关
      }
    },
    methods: {
      filterChange (val) {
        this.basicInfo.limit_buy_count = ''
      },
      searchStoreList (id) { // 查询仓库
        var _data = {branchId: id}
        getInfo.storeList(_data, (res) => {
          console.log(res, '仓库')
          if (res.message === 'ok') {
            this.storeList = res.content
            this.storeList.unshift({name: '全部', id: 0})
          } else {
            this.message('查询仓库失败', 'error')
          }
        })
      },
      searchCustomerType (id) { // 查询客资类型
        var _data = ''
        getInfo.client(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.customerTypeList = res.content.content
            this.customerTypeLoading = false
            if (id) {
              this.searchDetail(id)
            }
          }
        })
      },
      userTypeChange (val) { // 客资类型change事件
        if (val !== '1') {
          this.searchGoods('', '1')
          this.basicInfo.limit_product_type = ''
          this.selectDisabled = true
        } else {
          this.chooseGoodsInfo.firstCate = ''
          this.chooseGoodsInfo.secondCate = ''
          this.chooseGoodsInfo.fourCate = ''
          this.basicInfo.firstCate = ''
          this.basicInfo.secondCate = ''
          this.basicInfo.limit_brand_id = ''
          this.selectDisabled = false
        }
        this.resetTable()
        getInfo.getLabel({userType: val}, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.labelList = res.content
          }
        }) // 客户标签
      },
      visibleChange (a) {
        console.log(a)
        this.visible = a
      },
      // productTypeChange () { // 商品类型change
      //   if (this.visible === true) {
      //     this.goodsSearchList = []
      //     this.goodsList = []
      //     this.comboInfo = []
      //   }
      // },
      resetTable () { // 重置table
        if (this.visible === true) {
          this.goodsSearchList = []
          this.goodsList = []
          this.comboInfo = []
        }
      },
      handleAvatarSuccess (res, file) { // 上传图片成功
        console.log(res)
        if (res.message === 'ok') {
          this.basicInfo.cover_pic = res.content.imageUrl
          this.imgValid = true
        } else {
          this.imgValid = false
          this.message('上传图片失败', 'error')
        }
      },
      beforeAvatarUpload (file) { // 上传图片之前
        const isLt2M = file.size / 1024 / 1024 < 3
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        return isLt2M
      },
      nextStep (formName) { // 下一步
        if (this.basicInfo.promotion_icon === 2 && this.basicInfo.limit_satisfy_money === '') {
          this.message('请输入起购金额', 'error')
          return false
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.imgValid === true) {
              this.firstStep = false
              this.secondStep = true
            } else {
              this.message('请上传图片', 'error')
            }
          }
        })
        this.matchPromotionfeetype()
        // // console.log(formName)
        // this.firstStep = false
        // this.secondStep = true
        this.searchSalesCosts()
      },
      handleChooseGoods (id, group, type) { // 选择商品按钮
        switch (group) {
          case '1':
            if (this.basicInfo.limit_user_type !== '1') {
              this.chooseGoodsInfo.firstCate = this.basicInfo.firstCate
              this.chooseGoodsInfo.secondCate = this.basicInfo.secondCate
              this.chooseGoodsInfo.fourCate = this.basicInfo.limit_brand_id
              this.goodsDialog = true
              this.searchGoods(id, group)
            } else {
              this.goodsDialog = true
              this.searchGoods(id, group)
            }
            break
          case '2':
            if (id === '') {
              this.secondClassifyGroup = []
              this.threeClassifyGroup = []
              this.brandGroup = []
            } else {
              this.searchGoods(id, group)
            }
            if (type === '1') {
              this.basicInfo.secondCate = ''
              this.basicInfo.thirdCate = ''
              this.basicInfo.limit_brand_id = ''
              this.resetTable()
            } else {
              this.chooseGoodsInfo.secondCate = ''
              this.chooseGoodsInfo.thirdCate = ''
              this.chooseGoodsInfo.fourCate = ''
            }
            break
          default:
            if (id === '') {
              this.threeClassifyGroup = []
              this.brandGroup = []
            } else {
              this.searchGoods(id, group)
            }
            if (type === '1') {
              this.basicInfo.thirdCate = ''
              this.basicInfo.limit_brand_id = ''
              this.resetTable()
            } else {
              this.chooseGoodsInfo.thirdCate = ''
              this.chooseGoodsInfo.fourCate = ''
            }
            break
        }
      },
      searchSalesCosts () { // 查询促销费用
        var _data = {
          branchId: this.branchId,
          startTime: this.basicInfo.start_time,
          endTime: this.basicInfo.end_time,
          activityType: '1'
        }
        activity.cxfy.allList(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.salesCostsList = res.content
            this.saleCostLoading = false
          }
        })
      },
      handleChangeSalesCosts (val, index) { // 促销费用change事件
        // console.log(this.salesCostsList)
        for (var i = 0; i < this.salesCostsList.length; i++) {
          var element = this.salesCostsList[i]
          if (element.id === Number(val)) {
            this.selectSalesType[index] = element.promotionType
            // console.log(element.promotionType)
            // console.log(this.selectSalesType)
            if (element.promotionType === 3) {
              this.goodsList[index].providerDisabled = false
              this.goodsList[index].providerholdprice = this.goodsList[index].cxmls
              Vue.set(this.goodsList, index, this.goodsList[index])
              console.log(this.goodsList[index])
            } else if (element.promotionType === 2) {
              this.goodsList[index].providerDisabled = false
              this.goodsList[index].providerholdprice = 0
              this.goodsList[index].providerholdprice = this.goodsList[index].providerholdprice.toFixed(2)
              Vue.set(this.goodsList, index, this.goodsList[index])
              console.log(this.goodsList[index])
            } else if (element.promotionType === 1) {
              this.goodsList[index].providerDisabled = true
              this.goodsList[index].providerholdprice = 0.00
              this.goodsList[index].providerholdprice = this.goodsList[index].providerholdprice.toFixed(2)
              Vue.set(this.goodsList, index, this.goodsList[index])
              // console.log(this.goodsList[index])
            } else {
              this.goodsList[index].providerDisabled = false
            }
          }
        }
      },
      searchGoods (id, group) { // 查询商品分类方法
        getInfo.getCate({pid: id}, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            // console.log(res.content)
            if (group === '1') {
              this.firstClassifyGroup = res.content
            } else if (group === '2') {
              this.secondClassifyGroup = res.content
            } else if (group === '3') {
              this.threeClassifyGroup = res.content
              this.searchBrand(id)
            }
          }
        })
      },
      searchBrand (id) { // 查询品牌
        console.log(id)
        getInfo.getBrand({cateId: id}, (res) => {
          if (res.message === 'ok') {
            console.log(res)
            this.brandGroup = res.content
          }
        })
      },
      searchCouponGoods (isMaster, text) { // 查询商品
        console.log(isMaster)
        this.searchLoading = true
        var _data = this.chooseGoodsInfo
        _data.branchId = this.branchId // 分公司id
        _data.userType = this.basicInfo.limit_user_type // 客资类型
        _data.promotionType = 1 // 活动类型
        _data.flag = 1
        _data.isMaster = isMaster // 是否为主商品 主商品 1 副商品 0
        _data.startTime = this.basicInfo.start_time
        _data.endTime = this.basicInfo.end_time
        this.chooseGoodsInfo.page = text ? 1 : this.chooseGoodsInfo.page
        // _data.classId = this.basicInfo.limit_product_type === '40' ? [] : this.basicInfo.limit_product_type // 商品类型
        _data.classId = this.basicInfo.limit_product_type === '40' ? [40, 41] : [this.basicInfo.limit_product_type]
        _data.showType = [1, 3, 4, 10]
        console.log(_data)
        getInfo.searchProduct(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.searchLoading = false
            if (res.content.content !== null) {
              this.goodsSearchList = []
              for (var index = 0; index < res.content.content.length; index++) {
                // var eleGoods = this.goodsSearchList[index]
                var eleRes = res.content.content[index]
                this.goodsSearchList.push(this.goodsListMap(eleRes, isMaster))
                //   {
                //   // 'productName': eleRes.hmpName, // 商品名称
                //   // 'units': eleRes.hmpUnit, // 单位
                //   // 'productSize': eleRes.hmpNorms, // 规格
                //   // 'price': eleRes.hmpBuyPrice, // 系统售价
                //   'isActivity': eleRes.isActivity === null ? '' : eleRes.isActivity.join(','), // 当前活动 eleRes.isActivity
                //   'productid': eleRes.hmpId, // 商品id
                //   'name': eleRes.hmpName, // 商品名称
                //   'saleunit': eleRes.saleunit, // 销售单位
                //   'salenorm': eleRes.salenorm, // 销售规格
                //   'saleprice': eleRes.price === null ? '' : Number(eleRes.price).toFixed(2), // 系统售价
                //   // 'saleprice': eleRes.hmpBuyPrice, // 系统售价
                //   'operation': 0, // 操作
                //   'cgprice': Number(eleRes.proBuyPrice).toFixed(2), // 上次入库成本价
                //   // 'cgprice': eleRes.proBuyPrice, // 上次入库成本价
                //   'cgunit_convert': eleRes.CGUnitConvert, // 采购单位和最小单位转换值
                //   'num': '', // 数量
                //   'promotionfeetype': '', // 促销费用id
                //   'promotionprice': '', // 促销价
                //   'providerholdprice': '', // 供应商承担费用
                //   'saleunit_convert': eleRes.saleUnitConvert, // 销售单位和最小单位转换值
                //   'providerDisabled': false, // 供应商承担费用禁用
                //   'oldml': eleRes.price === null ? '' : (eleRes.price - eleRes.proBuyPrice).toFixed(2), // 原毛利 // 商品原毛利=商品系统售价-商品上次入库成本价
                //   // 'oldml': eleRes.hmpBuyPrice - eleRes.proBuyPrice, // 原毛利 // 商品原毛利=商品系统售价-商品上次入库成本价
                //   'cxml': '', // 促销毛利
                //   'cxmls': '', // 毛利损失
                //   'countState': false, // 计算状态
                //   'is_master': isMaster, // 是否为主商品
                //   'promotionproduct_id': '' // 商品主键ID
                // }
                // )
              }
              console.log(this.goodsSearchList)
              this.chooseGoodsInfo.total = res.content.count
              this.chooseGoodsInfo.page = res.content.page
              this.matchOperation(this.goodsSearchList, this.goodsList)
            } else {
              this.goodsSearchList = []
              this.chooseGoodsInfo.total = 0
            }
          } else {
            this.chooseGoodsInfo.total = 0
            this.searchLoading = false
            this.goodsSearchList = []
            this.message(res.message, 'error')
          }
        })
      },
      goodsListMap (eleRes, isMaster) { // 商品列表映射
        var goodsObj = {
          'stateName': eleRes.changeDes,
          'isActivity': eleRes.isActivity === null ? '' : eleRes.isActivity.join(','), // 当前活动 eleRes.isActivity
          'productid': eleRes.hmpId, // 商品id
          'name': eleRes.hmpName, // 商品名称
          'saleunit': eleRes.saleunit, // 销售单位
          'salenorm': eleRes.salenorm, // 销售规格
          'saleprice': eleRes.price === null ? '' : Number(eleRes.price).toFixed(2), // 系统售价
          'saleunitFlag': false,
          'salenormFlag': false,
          'salepriceFlag': false,
          'canNotSale': eleRes.canNotSale ? eleRes.canNotSale : '', // 商品不能卖 true 不能卖
          'priceChangeIng': eleRes.priceChangeIng ? eleRes.priceChangeIng : '', // 商品不能卖 true 不能卖
          // 'saleprice': eleRes.hmpBuyPrice, // 系统售价
          'operation': 0, // 操作
          'cgprice': Number(eleRes.proBuyPrice).toFixed(2), // 上次入库成本价
          // 'cgprice': eleRes.proBuyPrice, // 上次入库成本价
          'cgunit_convert': eleRes.CGUnitConvert, // 采购单位和最小单位转换值
          'num': '', // 数量
          'promotionfeetype': '', // 促销费用id
          'promotionprice': '', // 促销价
          'providerholdprice': '', // 供应商承担费用
          'saleunit_convert': eleRes.saleUnitConvert, // 销售单位和最小单位转换值
          'providerDisabled': false, // 供应商承担费用禁用
          'oldml': eleRes.price === null ? '' : (eleRes.price - eleRes.proBuyPrice).toFixed(2), // 原毛利 // 商品原毛利=商品系统售价-商品上次入库成本价
          // 'oldml': eleRes.hmpBuyPrice - eleRes.proBuyPrice, // 原毛利 // 商品原毛利=商品系统售价-商品上次入库成本价
          'cxml': '', // 促销毛利
          'cxmls': '', // 毛利损失
          'countState': false, // 计算状态
          'is_master': isMaster, // 是否为主商品
          'promotionproduct_id': '' // 商品主键ID
        }
        return goodsObj
      },
      addCode (row, data) { // 添加商品
        this.goodsList.push(row)
        row.promotionprice = ''
        row.num = ''
        row.providerDisabled = false
        row.promotionfeetype = ''
        row.providerholdprice = ''
        row.cxml = ''
        row.cxmls = ''
        row.countState = false
        data.operation = 1
        // this.resetChoseCode()
      },
      deleteCoupon (index, row) { // 删除优惠券
        this.$confirm('您确定要删除该条商品吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          for (var k = 0; k < this.goodsSearchList.length; k++) {
            var element = this.goodsSearchList[k]
            if (Number(element.productid) === Number(row.productid)) {
              element.operation = 0
            }
          }
          this.goodsList.splice(index, 1)
          console.log(this.goodsList)
          console.log(this.goodsSearchList)
          this.message('删除成功', 'success')
          this.computeComb()
          // if (arr.length === 0) {
          //   // this.resetPrimary()
          //   // this.inActivity = false
          //   // this.inActivityDetails = []
          // }
          // this.resetChoseCode()
        })
      },
      matchOperation (arr1, arr2) { // 查询时 匹配优惠券数组 和 已选则优惠券数组 显示 添加或撤回
        console.log(arguments)
        for (var i = 0; i < arr1.length; i++) {
          var allEle = arr1[i]
          if (arr2.length === 0) {
            arr1[i].operation = 0
          } else {
            for (var k = 0; k < arr2.length; k++) {
              var selectEle = arr2[k]
              if (Number(allEle.productid) === Number(selectEle.productid)) {
                // console.log('aaaa')
                arr1[i].operation = 1
              }
            }
          }
        }
      },
      selectChange (selection) { // table多选框
        this.selectGroup = selection
        console.log(this.selectGroup)
      },
      checkSelectAble (row, index) { // 添加后清空选择状态
        return row.operation !== 1
      },
      batchAdd () { // 商品批量添加
        this.goodsList = this.goodsList.concat(this.selectGroup)
        this.matchOperation(this.goodsSearchList, this.goodsList)
        this.$refs.table.clearSelection(this.selectGroup)
      },
      recallCode (row, arr) { // 撤回
        console.log(arguments)
        for (var i = 0; i < arr.length; i++) {
          var element = arr[i]
          if (Number(element.productid) === Number(row.productid)) {
            arr.splice(i, 1)
          }
        }
        row.operation = 0
      },
      handleCurrentChange (val) { // 分页
        console.log(val)
        this.chooseGoodsInfo.page = val
        this.searchCouponGoods(this.isMaster)
      },
      valueToTable (row, index, text) {
        var cgprice = this.goodsList[index].cgprice // 最后一次采购价
        var saleprice = this.goodsList[index].saleprice // 系统售价
        var promotionprice = this.goodsList[index].promotionprice // 促销价
        var num = this.goodsList[index].num // 数量
        var providerholdprice = this.goodsList[index].providerholdprice // 供应商承担金额
        if (text === '促销价') {
          // var num = this.goodsList[index].num // 数量
          // 商品原毛利=商品系统售价-商品上次入库成本价
          // 商品促销价=运营人员录入的价格
          // 商品促销毛利=商品促销价-商品上次入库成本价
          // 商品毛利损失=商品系统售价-商品促销价
          // this.goodsList[index].oldml = Number(saleprice) - Number(cgprice)
          if (this.moneyConfine(promotionprice, 'money')) {
            console.log(promotionprice)
            this.goodsList[index].cxml = (Number(promotionprice) - Number(cgprice)).toFixed(2)
            this.goodsList[index].cxmls = (Number(saleprice) - Number(promotionprice)).toFixed(2)
            this.goodsList[index].promotionprice = Number(this.goodsList[index].promotionprice).toFixed(2)
            // this.goodsList[index].cxml = (Number(promotionprice) - Number(cgprice))
            // this.goodsList[index].cxmls = (Number(saleprice) - Number(promotionprice))
            // this.goodsList[index].promotionprice = Number(this.goodsList[index].promotionprice)
            if (this.selectSalesType[index] === 3) { // 如果客资类型等于3 供应商承担金额 = 毛利损失
              this.goodsList[index].providerholdprice = this.goodsList[index].cxmls
            }
            if (Number(promotionprice) > (saleprice)) {
              this.goodsList[index].promotionprice = ''
              this.goodsList[index].cxml = ''
              this.goodsList[index].cxmls = ''
              // this.goodsList[index].cxmll = ''
              this.message('促销价小于系统售价', 'error')
            }
            if (promotionprice !== '' && num !== '') {
              this.goodsList[index].countState = true
              this.computeComb()
            } else {
              this.goodsList[index].countState = false
              // this.computeComb()
            }
          } else {
            this.goodsList[index].promotionprice = ''
            this.goodsList[index].cxml = ''
            this.goodsList[index].cxmls = ''
            this.message('金额必须大于0且最多有两位小数！', 'error')
          }
        } else if (text === '数量') {
          // if (this.goodsList[index].promotionprice === '') {
          //   this.message('请输入促销价', 'error')
          //   this.goodsList[index].num = ''
          // }
          if (this.moneyConfine(num, 'num')) {
            if (promotionprice !== '' && num !== '') {
              this.goodsList[index].countState = true
              this.computeComb()
            } else {
              this.goodsList[index].countState = false
              // this.computeComb()
            }
          } else {
            this.goodsList[index].num = ''
            this.message('请输入大于0的数值', 'error')
          }
        } else if (text === '供应商承担金额') {
          if (providerholdprice === '' || !this.selectSalesType[index]) {
            this.message('请输入促销价或请选择促销费用', 'error')
            this.goodsList[index].providerholdprice = ''
          } else {
            if (this.moneyConfine(providerholdprice, 'money')) {
              this.goodsList[index].providerholdprice = Number(this.goodsList[index].providerholdprice).toFixed(2)
              switch (this.selectSalesType[index]) {
                case 3:
                  if (Number(providerholdprice) < Number(this.goodsList[index].cxmls)) {
                    this.message('供应商承担金额大于等于毛利损失', 'error')
                    this.goodsList[index].providerholdprice = this.goodsList[index].cxmls
                  }
                  break
                case 2:
                  if (Number(providerholdprice) < 0) {
                    this.message('供应商承担金额大于等于毛利损失', 'error')
                    this.goodsList[index].providerholdprice = this.goodsList[index].cxmls
                  }
                  break
                default:
                  break
              }
            } else {
              this.goodsList[index].providerholdprice = ''
              this.message('金额必须大于0且最多有两位小数！', 'error')
            }
          }
        }
        // 套餐原价=商品系统售价*数量之和
        // 套餐成本价=商品上次入库成本价*数量之和
        // 套餐原毛利=商品原毛利*数量之和
        // 套餐促销价=商品促销价*数量之和
        // 套餐促销毛利=商品促销毛利*数量之和
        // 套餐毛利损失=套餐原毛利-套餐促销毛利
        // 套餐促销毛利率=（套餐促销价-套餐成本价）/套餐成本价
      },
      computeComb () { // 计算套餐
        // console.log(this.goodsList)
        if (this.goodsList.length !== 0) {
          var obj = {
            tcyuanjia: 0,
            tcchengbenjia: 0,
            tcyuanmaoli: 0,
            tccuxiaojia: 0,
            tccuxiaomaoli: 0,
            tcmaolisunshi: 0,
            tccuxiaomaolilv: 0
          }
          for (const item in this.goodsList) {
            if (this.goodsList[item].countState === true) {
              obj.tcyuanjia = obj.tcyuanjia + this.goodsList[item].saleprice * this.goodsList[item].num
              obj.tcchengbenjia = obj.tcchengbenjia + this.goodsList[item].cgprice * this.goodsList[item].num
              obj.tcyuanmaoli = obj.tcyuanmaoli + this.goodsList[item].oldml * this.goodsList[item].num
              obj.tccuxiaojia = obj.tccuxiaojia + this.goodsList[item].promotionprice * this.goodsList[item].num
              obj.tccuxiaomaoli = obj.tccuxiaomaoli + this.goodsList[item].cxml * this.goodsList[item].num
            }
          }
          obj.tcyuanjia = obj.tcyuanjia.toFixed(2)
          obj.tcchengbenjia = obj.tcchengbenjia.toFixed(2)
          obj.tcyuanmaoli = obj.tcyuanmaoli.toFixed(2)
          obj.tccuxiaojia = obj.tccuxiaojia.toFixed(2)
          obj.tccuxiaomaoli = obj.tccuxiaomaoli.toFixed(2)
          obj.tcmaolisunshi = (obj.tcyuanmaoli - obj.tccuxiaomaoli).toFixed(2)
          obj.tccuxiaomaolilv = Number(obj.tcchengbenjia) === 0 ? '100' : (((Number(obj.tccuxiaojia) - Number(obj.tcchengbenjia)) / Number(obj.tcchengbenjia)) * 100).toFixed(2)
          // console.log(obj.tccuxiaojia, typeof (obj.tccuxiaojia), obj.tcchengbenjia, typeof (obj.tcchengbenjia))
          // obj.tccuxiaomaolilv = ((obj.tccuxiaojia - obj.tcchengbenjia) / obj.tcchengbenjia)
          // this.basicInfo.grossProfitRate = obj.tccuxiaomaolilv
          this.comboInfo = []
          this.comboInfo.push(obj)
        } else {
          this.comboInfo = []
        }
      },
      moneyConfine (val, type) { // 验证为大于等于0 且保留两位小数
        var str = val.toString().indexOf('.')
        // var zero = val.toString().indexOf('0')
        var numlength = 0
        if (str !== -1) {
          var index = val.substring(str + 1, val.length)
          numlength = index.length
        }
        if (type === 'money') {
          if (isNaN(val) || (val < 0) || (numlength > 2) || val === '') {
            return false
          } else {
            return true
          }
        } else {
          if (isNaN(val) || (val <= 0) || (numlength > 0) || val === '') {
            return false
          } else {
            return true
          }
        }
      },
      matchPromotionfeetype () { // 匹配返回的促销费用 有没有过期
        console.log(this.goodsList)
        console.log(this.salesCostsList)
        for (let i = 0; i < this.goodsList.length; i++) {
          var flag = false
          const item = this.goodsList[i]
          for (let k = 0; k < this.salesCostsList.length; k++) {
            const element = this.salesCostsList[k]
            // console.log(item.promotionfeetype)
            // console.log(element.id)
            if (item.promotionfeetype === element.id.toString()) {
              // console.log('存在')
              flag = true
              // return false
            } else {
              // console.log('不存在')
              if (k === this.salesCostsList.length - 1 && flag === false) {
                item.promotionfeetype = ''
              }
            }
          }
        }
      },
      searchDetail (id) { // 查询详情 详情回填
        activity.sphd.detail({id: id}, (res) => {
          console.log(res, '套餐的详情')
          if (res.message === 'ok') {
            this.detailData = res.content
            if (this.detailData.limit_usertypetag_id && this.detailData.limit_usertypetag_id !== '0') {
              this.arr = this.detailData.limit_usertypetag_id.split(',').map(value => {
                return parseInt(value)
              })
            } else {
              this.arr = []
            }
            this.showBranchName = res.content.branchName // 分公司
            this.showDeptName = res.content.departName // 部门
            this.basicInfo = {
              limit_usertypetag_id: this.arr, // 客户标签
              limit_client: res.content.client.toString(), // 设备类型
              promotion_icon: Number(res.content.promotion_icon), // 标签类型
              limit_branch_id: res.content.limit_branch_id, // 页面展示的公司名id
              limit_department: res.content.limit_department, // 页面展示的部门id
              limit_store_id: Number(res.content.limit_store_id), // 所属仓库
              limit_user_type: String(res.content.limit_user_type), // 客资类型
              firstCate: res.content.limit_cateid !== '' ? JSON.parse(res.content.limit_cateid).cateid1 : '', // 一级分类
              secondCate: res.content.limit_cateid !== '' ? JSON.parse(res.content.limit_cateid).cateid2 : '', // 二级分类
              limit_brand_id: res.content.brand_id, // 品牌ID
              limit_product_type: res.content.product_type === 0 ? '' : res.content.product_type.toString(), // 商品类型
              promotion_name: res.content.promotion_name, // 套餐名称
              start_time: res.content.start_time, // 活动开始时间
              end_time: res.content.end_time, // 活动结束时间
              limit_satisfy_money: res.content.limit_satisfy_money === '' ? '' : res.content.limit_satisfy_money / 100, // 起购金额
              limit_sell_count: res.content.limit_sell_count, // 销售上线
              limit_buy_filter: String(res.content.limit_buy_filter), // 限购条件
              limit_buy_count: res.content.limit_buy_count, // 限购数量
              describe: res.content.describe, // 描述
              remark: res.content.remark, // 备注
              cover_pic: res.content.cover_pic, // 封面头图URL
              // iscaogao: '', // 是否草稿
              product: '', // 商品
              startStopTime: [res.content.start_time, res.content.end_time], // 活动开始结束时间
              grossProfitRate: res.content.cxmll
            }
            this.searchSalesCosts()
            this.imgValid = true
            this.searchGoods(this.basicInfo.firstCate, '2') // 查询商品分类
            this.searchGoods(this.basicInfo.secondCate, '3') // 查询品牌
            this.goodsList = []
            for (let index = 0; index < res.content.main_product.length; index++) {
              const eleRes = res.content.main_product[index]
              if (eleRes.status === 1) {
                this.goodsList.push(eleRes)
                this.goodsList[index].promotionfeetype = eleRes.promotionfeetype.toString()
                this.goodsList[index].num = eleRes.pnum
                this.goodsList[index].promotionprice = eleRes.price_real
                // this.goodsList[index].num = eleRes.pnum
                // eleRes.price_total = (eleRes.price_total / 100).toFixed(2)
                eleRes.cgprice = (eleRes.cgprice / 100).toFixed(2)
                eleRes.oldml = (eleRes.oldml / 100).toFixed(2)
                eleRes.promotionprice = (eleRes.promotionprice / 100).toFixed(2)
                // eleRes.cxmll = (eleRes.cxmll / 100).toFixed(4)
                eleRes.cxml = (eleRes.cxml / 100).toFixed(2)
                eleRes.cxmls = (eleRes.cxmls / 100).toFixed(2)
                eleRes.saleprice = (eleRes.saleprice / 100).toFixed(2)
                var self = this
                setTimeout(() => {
                  self.handleChangeSalesCosts(eleRes.promotionfeetype, index)
                }, 500)
              }
            }
            const comboArr = [{
              tcyuanjia: (res.content.price_total / 100).toFixed(2), // 套餐原价
              tcchengbenjia: (res.content.cgprice / 100).toFixed(2), // 套餐成本价
              tcyuanmaoli: (res.content.oldml / 100).toFixed(2), // 套餐原毛利
              tccuxiaojia: (res.content.price_real_total / 100).toFixed(2), // 套餐促销价
              tccuxiaomaoli: (res.content.cxml / 100).toFixed(2), // 套餐促销毛利
              tccuxiaomaolilv: res.content.cxmll, // 套餐促销毛利率
              tcmaolisunshi: (res.content.cxmlss / 100).toFixed(2) // 套餐促销毛利损失
            }]
            this.comboInfo = comboArr
            this.$store.dispatch('pageLoading', false)
          } else {
            this.$store.dispatch('pageLoading', false)
            this.message('查看详情失败', 'error')
          }
        })
      },
      createData (buttonType) {
        var _data = Object.assign({}, this.basicInfo)
        _data.iscaogao = buttonType // 是否为草稿 1是草稿 2不是   提交
        _data.promotion_id = this.isCreateOrUpdate === 'update' ? this.detailData.promotion_id : ''
        _data.id = this.isCreateOrUpdate === 'update' ? this.detailData.id : ''
        _data.newBranchId = this.branchOrgId // 新公司id
        _data.gwId = this.roleId // 岗位id
        _data.uorId = this.uorId
        _data.userId = this.userId
        _data.promotion_icon = this.basicInfo.promotion_icon // 标签类型
        _data.limit_usertypetag_id = this.basicInfo.limit_usertypetag_id.join(',') // 客户标签
        _data.userName = this.userName
        _data.grossProfitRate = this.comboInfo.length !== 0 ? this.comboInfo[0].tccuxiaomaolilv : ''
        _data.limit_satisfy_money = this.basicInfo.limit_satisfy_money !== '' ? this.basicInfo.limit_satisfy_money * 100 : ''
        _data.limit_cateid = {
          cateid1: this.basicInfo.firstCate,
          cateid2: this.basicInfo.secondCate
        }
        var product = JSON.parse(JSON.stringify(this.goodsList))
        for (let index = 0; index < product.length; index++) {
          const element = product[index]
          element.cgprice = (element.cgprice * 100).toFixed(0) // 上次入库成本价
          element.promotionprice = (element.promotionprice * 100).toFixed(0) // 促销价
          element.providerholdprice = (element.providerholdprice * 100).toFixed(0) // 供应商承担费用
          element.saleprice = (element.saleprice * 100).toFixed(0) // 系统售价
        }
        _data.product = product
        return _data
      },
      onSubmit (buttonType, formName) { // 提交
        this.formValidation()
        console.log(formName)
        console.log(this.$refs)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var _data = this.createData(buttonType)
            console.log(_data)
            if (this.goodsVaild === true) {
              activity.sphd.tc.pttc[this.isCreateOrUpdate](_data, (res) => {
                console.log(res)
                if (res.message === 'ok') {
                  this.message(this.text + '成功', 'success')
                  this.cancel(this.menuId)
                  this.$store.dispatch('pttcState', this.$store.state.updateState.pttcState + 1)
                  // this.subDisabled = true
                } else if (res.code === 5050) {
                  // this.subDisabled = false
                  // this.goodsListFlag = false
                  this.changeGoodsList = []
                  this.checkOutChangeGoods(res)
                  this.changeGoodFlag = true
                  this.message(res.message, 'error')
                } else {
                  // this.cancel(this.menuId)
                  this.message(res.message, 'error')
                }
              })
              console.log(this.goodsVaild)
            } else {
              console.log(this.goodsVaild)
            }
          }
        })
      },
      checkOutChangeGoods (res) { // 校验调价商品
        res.content.forEach((element, index) => {
          this.goodsList.forEach((element2, index2) => {
            if (Number(element.hmpId) === Number(element2.productid)) {
              element2.saleunitFlag = element.saleUnitChange
              element2.salenormFlag = element.saleNormChange
              element2.salepriceFlag = element.priceChange
              // element2.canNotSale = element.canNotSale
              this.tableIndex.push(index2)
            }
          })
          this.changeGoodsList.push(this.goodsListMap(element, ''))
        })
        console.log(this.changeGoodsList)
      },
      tableRowClassName (row, index, ind) { // 给table加某一行的样式
        for (let index2 = 0; index2 < this.tableIndex.length; index2++) {
          // console.log(this.tableIndex)
          const element = this.tableIndex[index2]
          if (index === element) {
            // console.log(index2, element)
            // console.log('aaaaa')
            return 'highlight'
          }
        }
      },
      changeGoodsClick () { // 一键修改
        for (let index = 0; index < this.goodsList.length; index++) {
          const element = this.goodsList[index]
          for (let index2 = 0; index2 < this.changeGoodsList.length; index2++) {
            const element2 = this.changeGoodsList[index2]
            if (element.productid === element2.productid) {
              if (element2.canNotSale === true || element2.priceChangeIng === true) {
                console.log('删除')
                for (var k = 0; k < this.goodsSearchList.length; k++) {
                  var element3 = this.goodsSearchList[k]
                  if (Number(element3.productid) === Number(element.productid)) {
                    element3.operation = 0
                  }
                }
                this.goodsList.splice(index, 1)
                index = index - 1
                this.computeComb()
              } else {
                element.saleunit = element2.saleunit
                element.salenorm = element2.salenorm
                element.saleprice = element2.saleprice
                element.oldml = element.saleprice === null ? '' : (Number(element.saleprice) - Number(element.cgprice)).toFixed(2)
                this.valueToTable('', index, '促销价')
                this.isRed = false
                this.isGreen = true
              }
            }
          }
        }
      },
      formValidation () { // 验证
        if (this.goodsList.length !== 0) {
          for (let index = 0; index < this.goodsList.length; index++) {
            const element = this.goodsList[index]
            if (this.selectSalesType[index] === 1 || this.selectSalesType[index] === 2) {
              if (element.promotionprice !== '' && element.num !== '' && element.promotionfeetype !== '' && element.providerholdprice !== '') {
                this.goodsVaild = true
              } else {
                this.message('第' + (index + 1) + '促销价/数量/促销费用/供应商承担金额不为空或格式错误', 'error')
                this.goodsVaild = false
                return false
              }
            } else {
              if (element.promotionprice !== '' && element.num !== '' && element.promotionfeetype !== '') {
                this.goodsVaild = true
              } else {
                this.message('第' + (index + 1) + '促销价/数量/促销费用不为空或格式错误', 'error')
                this.goodsVaild = false
                return false
              }
            }
          }
        } else {
          this.goodsVaild = false
          this.message('请添加商品', 'error')
        }
        // console.log(moment(this.basicInfo.start_time).valueOf())
        // console.log(moment(this.basicInfo.start_time).valueOf())
        // console.log(moment().valueOf(new Date().toLocaleString()))
        if (moment(this.basicInfo.start_time).valueOf() < moment().valueOf(new Date().toLocaleString())) {
          this.message('活动开始时间大于当前时间', 'error')
          this.basicInfo.startStopTime = []
        }
      },
      cancel (id, num) { // 取消
        if (num) {
          this.$confirm('确定要取消？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('delTab', {id: id})
          }).catch(() => {
          })
        } else {
          this.$store.dispatch('delTab', {id: id})
        }
      },
      goBack () {
        this.firstStep = true
        this.secondStep = false
      },
      daterangeFormat (t) { // 时间段格式化
        console.log(t)
        if (t) {
          this.basicInfo.start_time = t[0]
          this.basicInfo.end_time = t[1]
          if (moment(this.basicInfo.start_time).valueOf() >= moment(this.basicInfo.end_time).valueOf()) {
            this.message('活动开始时间小于活动结束时间', 'error')
            this.basicInfo.startStopTime = []
          }
        }
      },
      message (text, type) { // 消息提示
        this.$message({
          showClose: true,
          message: text,
          type: type
        })
      }
    },
    computed: {
      update_state: function () {
        // console.log(state.updateState.dhmState)
        return this.$store.state.updateState.pttcState
      },
      userName: function () {
        if (!this.$store.state.user.info.user_name) {
          this.$store.dispatch('SET_TOKEN')
        }
        return this.$store.state.user.info.user_name
      },
      userId: function () {
        return this.$store.state.user.info.user_id
      },
      roleId: function () {
        return this.$store.state.user.info.roleid
      },
      branchName: function () {
        return this.$store.state.user.info.branchId === 1 ? '总公司' : this.$store.state.user.info.branchName
      },
      branchId: function () {
        return this.$store.state.user.info.branchId
      },
      deptName: function () {
        return this.$store.state.user.info.parOrgName
      },
      deptId: function () {
        return this.$store.state.user.info.or_org_id
      },
      branchOrgId: function () {
        return this.$store.state.user.info.branchOrgId
      },
      uorId: function () {
        return this.$store.state.user.info.uor_id
      },
      user_telphone: function () {
        return this.$store.state.user.info.user_telphone
      }
    },
    created () {
      getInfo.getLabel({userType: 1}, (res) => {
        if (res.message === 'ok') {
          res.content.forEach((item, index) => {
//            item.disabled = true
            if (item.labelCode !== 6) {
              item.disabled = true
            }
          })
          this.labelList = res.content
        }
      }) // 客户标签
      this.url = 'http://' + apiHost.newCms + ':20000' + apiURL.goodsSet_uploadImage
      this.imgHost = apiHost.imgHost
      console.log(apiHost)
      // console.log(apiURL)
      // this.url = 'http://192.168.88.132:20000' + apiURL.goodsSet_uploadImage
      console.log(this.url)
      this.menuId = this.$store.state.tab.menuId
      console.log(this.$store.state.tab.uid)
      if (this.$store.state.tab.uid) {
        console.log(this.$store.state.tab)
        if (this.menuId === 'pttc_fz') {
          this.isCreateOrUpdate = 'create'
          this.text = '复制'
          this.showBranchName = this.branchName // 新增是公司是当前用户的公司名称
          this.showDeptName = this.deptName // 新增是公司是当前用户的公司名称
          this.basicInfo.limit_branch_id = this.branchId
          this.basicInfo.limit_department = this.deptId
        } else {
          this.isCreateOrUpdate = 'update'
          this.text = '编辑'
        }
        this.$store.dispatch('pageLoading', true)
        this.searchCustomerType(this.$store.state.tab.uid) // 查询客资类型
        this.searchStoreList(this.branchId)
      } else {
        this.isCreateOrUpdate = 'create'
        this.text = '新增'
        this.searchCustomerType(this.$store.state.tab.uid) // 查询客资类型
        this.showBranchName = this.branchName // 新增是公司是当前用户的公司名称
        this.showDeptName = this.deptName // 新增是公司是当前用户的公司名称
        this.basicInfo.limit_branch_id = this.branchId
        this.basicInfo.limit_department = this.deptId
        this.searchStoreList(this.branchId)
      }
      console.log(this.isCreateOrUpdate)
    }
    // watch: {
    //   comboInfo (curVal, oldVal) {  // 监听 更新状态 查询list
    //     console.log('zc')
    //     this.computeComb()
    //   }
    // }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-table .highlight {
    background: #bcdcf7
  }
  .el-table .red {
    color: red
  }
  .el-table .green {
    color: rgb(72, 185, 72)
  }
</style>
